<template>
  <div class="square-lists">
    <square-search @updateQueryParams="handleUpdateQueryParams"></square-search>
    <!-- 当有数据时显示任务列表 -->
    <template v-if="tasks.data.total > 0">
      <template v-for="(item, index) in tasks.data.records" :key="index">
        <square-list-items :show-data="item"></square-list-items>
      </template>
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="tasks.data.total"
          :page-size="queryParams.pageSize"
          :current-page="currentPage"
          @current-change="fetchTasks"
        />
      </div>
    </template>
    <!--当没有数据时显示空状态 -->
    <el-empty v-else-if="tasks.data.total === 0" description="没有找到任务"></el-empty>
    <div v-else-if="tasks.data.total === -1" style="position: relative; height: 300px">
      <loader v-if="loading" color="#fff" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import squareSearch from './square-search.vue'
import squareListItems from './square-list-items.vue'
import { queryTasksWithConditions } from '@/service/taskdetail/taskdetail.ts'
import { ElMessage } from 'element-plus'
import Loader from '@/components/loader/loader.vue'

const loading = ref(true)
const currentPage = ref(1)

// 接收从父组件传来的 queryParams
const props = defineProps<{
  queryParams: {
    page: number
    pageSize: number
    projectType?: string
    taskName?: string
    taskRole?: string
    taskPeriod?: string
    taskScoreMax?: number
    taskScoreMin?: number
  }
}>()

const emits = defineEmits(['updateQueryParams'])
function handleUpdateQueryParams(newParams: any) {
  // 发送事件给父组件，让父组件处理queryParams的更新
  emits('updateQueryParams', newParams)
}
const tasks = ref({ data: { records: [], total: -1 } })

// 监听 queryParams 的变化
watch(
  () => props.queryParams,
  () => {
    fetchTasks()
  },
  { immediate: true, deep: true }
)

async function fetchTasks(page: number = props.queryParams.page) {
  try {
    loading.value = true
    // 重置任务列表，避免旧数据残留
    tasks.value = { data: { records: [], total: -1 } }
    const response = await queryTasksWithConditions({ ...props.queryParams, page })
    tasks.value.data = response.data
    currentPage.value = page
    console.log('任务列表:', tasks.value.data.records)
    loading.value = false
    window.scrollTo(0, 0)
  } catch (error) {
    ElMessage.error('网络异常，请刷新重试')
    console.error('获取任务列表失败', error)
  }
}
</script>

<style lang="less" scoped>
.square-lists {
  box-sizing: border-box;
  width: 850px;
  background-color: #fff;
  border-radius: 10px;
  padding: 0 40px;
  .fenye {
    padding: 20px 0;
    display: flex;
    justify-content: center;
  }
}
</style>
